#include "stdafx.h"

#include "cloud.h"

Cloud::Cloud( Vector2 origin, Color &color ) : mColor( color )
{
    int r = (int) sqrt( float( DEFAULT_CLOUD_SIZE ) );
    int x = 0, y = 0;

    // Temporary storage
    Shape *shapes[DEFAULT_CLOUD_SIZE];

    mOrigin = origin;
    mColor  = color;

    mDroplets = new LinkedList<Droplet *>;

    // Build droplets
    for( int i = 0 ; i < DEFAULT_CLOUD_SIZE ; ++i )
    {
        if( i >= r && i % r == 0 )
        {
            x = 0;
            ++y;
        }

        CircleShape *shape = World::CircleShapeNew( Vector2( x++ * DEFAULT_CLOUD_DISPLACEMENT + origin.x, y * DEFAULT_CLOUD_DISPLACEMENT + origin.y ), 3.0f );
        Droplet *droplet = new Droplet( shape ); 

        mDroplets->Add( droplet );
        shapes[i] = shape;
    }

    // Build spring system
    for( int i = 0 ; i < DEFAULT_CLOUD_SIZE ; ++i )
    {
        if( (i / r) == (r - 1) )
        {
            if( (i + 1) % r != 0 )
            {
                World::SpringNew( shapes[i], shapes[i + 1], 0.06f, 0.2f, 0.6f );
            }
        }
        else
        {
            World::SpringNew( shapes[i], shapes[i + r], 0.06f, 0.2f, 0.6f );

            if( (i + 1) % r != 0 )
            {
                World::SpringNew( shapes[i], shapes[i + 1], 0.06f, 0.2f, 0.6f );
            }
        }
    }
}

Cloud::~Cloud( void )
{
    delete mDroplets;
}

void Cloud::SetTextureName( const GLuint textureName )
{
    mTextureName = textureName;
}

void Cloud::Render( void )
{
    glEnable( GL_BLEND );
    glBindTexture( GL_TEXTURE_2D, mTextureName );

    glColor4ub( mColor.r, mColor.g, mColor.b, 255 );

    do
    {
        Droplet *droplet = mDroplets->GetNext();

        droplet->Render();
    } while( mDroplets->HasNext() );
}